//
//  StoreModel.m
//  huhu
//
//  Created by gullmei on 15/10/25.
//  Copyright © 2015年 gullmei. All rights reserved.
//

#import "StoreModel.h"
#include <objc/runtime.h>
#import  "NSStringEX.h"

#define  DIC_CACHE       @"DIC_CACHE.txt"
#define  USER_CACHE      @"userID"
@implementation StoreModel

@synthesize storeDic = _storeDic;
@synthesize userID = _userID;
- (id)init
{
    self = [super init];
    if (self) {
        _storeDic = [[NSMutableDictionary alloc] init];
        _userID = @"";
    }
    return self;
}
#pragma mark - 存储
-(void)restoreData
{
    //对象反序列化
    @try {
        NSString *   filePath = [self createlistWithName:DIC_CACHE];
        NSMutableDictionary* tempdic = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        if(tempdic != nil)
        {
            self.storeDic = tempdic;
        }
        
        filePath = [self createlistWithName:USER_CACHE];
        NSString*  tempstr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        if(tempstr != nil)
        {
            self.userID = tempstr;
        }
    }
    @catch (NSException * e) {
        
    }
    @finally {
        
    }
}
//保存数据
-(void)Save
{
    //对象序列化
    @try {
        
        NSString * filePath = nil;
        
        filePath = [self createlistWithName:DIC_CACHE];
        [NSKeyedArchiver archiveRootObject:self.storeDic toFile:filePath];
        
        filePath = [self createlistWithName:USER_CACHE];
        [NSKeyedArchiver archiveRootObject:self.userID toFile:filePath];
        
    }
    @catch (NSException * e) {
        
    }
    @finally {
        
    }
}

- (NSString * )createlistWithName:(NSString *)name
{
    NSFileManager * manager = [NSFileManager defaultManager];
    NSString * pre = [NSString DocPath];
    NSString * fullPath = [NSString stringWithFormat:@"%@/contents/",pre];
    
    BOOL dir = 1;
    if (![manager fileExistsAtPath:fullPath isDirectory:&dir])
    {
        [manager createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    fullPath = [fullPath stringByAppendingString:name];
    dir = 0;
    if (![manager fileExistsAtPath:fullPath isDirectory:&dir])
    {
        [manager createFileAtPath:fullPath contents:nil attributes:nil];
    }
    //MLOG(@"%@",fullPath);
    return fullPath;
}

@end
